<?php
namespace app\api\service;
use think\Controller;
use think\Db;
use think\Exception;

class Partner extends Controller {
    static protected $err_code = 0;
    //申请成为合伙人接口
    static public function partner_create($param) {
        if( !isset($param['id']) || !isset($param['member_id']) || !isset($param['proposer']) || !isset($param['card_no'])
            || !isset($param['id_card_front']) || !isset($param['id_card_in_hand']) || !isset($param['id_card_verso']) || !isset($param['level'])
            || !isset($param['province']) || !isset($param['city']) || !isset($param['area']) || !isset($param['street'])
            || !isset($param['duty_province']) || !isset($param['duty_city']) || !isset($param['duty_area'])
            || !isset($param['address']) || !isset($param['lat'])  || !isset($param['lon'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        /*调用验证器 验证数据*/
        $validate = validate('Partner');
        //判断是否可以申请

        if (!$validate->check($param)) {
            return ['code'=>$validate->getError(),'msg'=> '提交资料不完整，请确认'];
        }

        // 根据地址名称获取地址ID
        $scope = get_scope_id($param['province'], $param['city'], $param['area'], $param['street']);
        $data = [
            'member_id' => $param['member_id']
            ,'proposer' => $param['proposer']
            ,'card_no' => $param['card_no']
            ,'id_card_in_hand' => $param['id_card_in_hand']
            ,'id_card_front' => $param['id_card_front']
            ,'id_card_verso' => $param['id_card_verso']
            ,'level' => $param['level']
            
            ,'province' => $scope['province']
            ,'city' => $scope['city']
            ,'area' => $scope['area']
            ,'street' => $scope['street']
            
            ,'address' => $param['address']
            ,'mobile' => $param['mobile'] // 申请时间
            ,'lat' => $param['lat']
            ,'lon' => $param['lon']
            ,'audit_status' => 1
            ,'apply_time' => time() // 申请时间
        ];

        // 启动事务
        Db::startTrans();
        try{
            $id = $param['id'];
            $duty_data = [
                'province' => $param['duty_province'],
                'city' => $param['duty_city'],
                'area' => $param['duty_area'],
                'level' => $param['level']
            ];


            if ($id > 0) {
                Db::table('mob_partner')->where('id', $id)->update($data);
                // 更新负责区域数据
                Db::table('mob_duty_area')->where('member_id', $param['member_id'])->where('member_type', 3)->update($duty_data);

            } else {

                // 新增记录 先检查是否存在信息相同的经销商店（店铺名字，身份证，用户）
                $check_repair_name = Db::table('mob_partner')->field('id')->where('member_id', $param['member_id'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400052;  //用户已申请维修店
                    throw new \Exception('FAULT');
                }
                $check_repair_name = Db::table('mob_partner')->field('id')->where('card_no', $param['card_no'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400064;  //身份证号码已申请维修店
                    throw new \Exception('FAULT');
                }

                $id = Db::table('mob_partner')->insertGetId($data);
                // 组装负责区域数据
                $duty_data['member_id'] = $param['member_id'];
                $duty_data['member_type'] = 3;
                Db::table('mob_duty_area')->insertGetId($duty_data);
            }

            // 提交事务
            Db::commit();
            return ['data'=>['partner_id' => $id],'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    //审核合伙人接口
    static public function partner_audit($param) {
        if( !isset($param['member_id']) || !isset($param['partner_id'])
            || !isset($param['auditor']) || !isset($param['audit_status'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            $data = [
                'auditor' => $param['auditor']
                ,'audit_status' => $param['audit_status']
                ,'audit_time' => time()
            ];
            Db::table('mob_partner')->where("id",$param['partner_id'])->update($data);
            Db::commit();
            return ['code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 获取合伙人信息接口
    static public function partner_info($param) {
        if( !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        $partner = Db::table('mob_partner')->where("member_id",$param['member_id'])->find();

        try{
            // 获取自己的负责区域
            $duty_area = Db::table('mob_duty_area')->where("member_id",$param['member_id'])->where('member_type', 3)->find();
            $where['audit_status'] = 1; // 统计待审核的  维修店和经销商
            switch ($partner['level']) {
                case 1: // 省级
                    $where['province'] = $duty_area['province'];
                    break;
                case 2: // 市级
                    $where['city'] = $duty_area['city'];
                    break;
                case 3: // 区县级
                    $where['area'] = $duty_area['area'];
                    break;
                case 4: // 街道级
                    $where['street'] = $duty_area['street'];
                    break;
                default:
                    break;
            }
            // 统计自己负责区域的待审核维修店
            $no_audit_repair = Db::table('mob_repair')->where($where)->count();

            // 统计自己负责区域的待审核经销商
            $where['level'] = $partner['level'];
            $no_audit_dealer = Db::table('mob_dealer')->where($where)->count();

            // 统计自己账户金额
            $money_where['member_id'] =  $param['member_id'];
            $money = Db::table('mob_partner')->where($money_where)->value('money');

            return [
                'data'=>[
                    'partner' => $partner,
                    'no_audit_repair' => $no_audit_repair,
                    'no_audit_dealer' =>  $no_audit_dealer,
                    'money' => $money
                ],'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 获取合伙人团队接口
    static public function partner_team($param) {
        if( !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            // 获取自己的信息
            $this_info = Db::table('mob_duty_area')->field('level, province, city, area, street')
                ->where('member_id', $param['member_id'])->where('member_type', 3)->order('id desc')->find();
            $where['da.member_type'] = 3;
            $where['da.level'] = $this_info['level'];
            $where['p.audit_status'] = 2;  // 只获取已通过审核的合伙人
            $data[] = $this_info;
            switch ($this_info['level']) {
                case 1: // 省级
                    $where['da.province'] = $this_info['province'];
                    break;
                case 2: // 市级
                    $where['da.city'] = $this_info['city'];
                    break;
                case 3: // 区县级
                    $where['da.area'] = $this_info['area'];
                    break;
                case 4: // 街道级
                    $where['da.street'] = $this_info['street'];
                    break;
                default:
                    self::$err_code = 400083;
                    throw new \Exception('FAULT');
                    break;
            }
            $region = Db::table('mob_region')->where('region_id', 'in', [$this_info['province'], $this_info['city'], $this_info['area'], $this_info['street']])->select();
            $partners = Db::table('mob_duty_area')->alias('da')
                ->field('p.id, p.member_id, p.proposer, p.audit_time, mri.headimgurl, mri.sex')
                ->join('mob_partner p', 'p.member_id = da.member_id and da.member_type = 3', 'LEFT')
                ->join('mob_member_role_info mri', 'mri.member_id = p.member_id and mri.type = 3', 'LEFT')
                ->where($where)->select();
            $k = 1;
            $data = [];
            foreach ($partners as $v) {
                if ($v['member_id'] == $param['member_id']) {
                    $data[0] = $v;
                } else {
                    $data[$k] = $v;
                    $k++;
                }
            }
            ksort($data);
            return ['data'=>['partners' => $data, 'level' => $this_info['level'], 'region' =>  $region],'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取合伙人首页数据
    static public function partner_index_data($param) {
        if( !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            // 维修店团队信息
            $param['audit_status'] = 1; // 获取待审核的维修店
            $repair_team = self::repair_team($param);
            //dump($repair_team);
            if ($repair_team['code'] != 200) {
                self::$err_code = 400091;
                throw new \Exception('FAULT');
            }
            //dump($repair_team);
            // 经销商团队
            $dealer_team = self::dealer_team($param);
            //dump($dealer_team);
            // 合伙人基本资料
            $member_info = Db::table('mob_member_role_info')->where('member_id', $param['member_id'])->where('type', 3)->find();

            // 合伙人级别
            $level = Db::table('mob_duty_area')->where('member_id', $param['member_id'])->where('member_type', 3)->order('id desc')->value('level');

            $data = [
                'repair_team' => $repair_team['data'],
                'dealer_team' => $dealer_team['data'],
                'member_info' => $member_info,
                'level' => $level
            ];

            return ['code' => 200, 'data' => $data,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取经销商团队
    static public function dealer_team($param) {
        if( !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
//            Db::listen(function($sql, $time, $explain){
//                // 记录SQL
//                echo $sql. ' ['.$time.'s]' . " \n ";
//            });
            // 获取合伙人负责区域信息
            $this_info = Db::table('mob_duty_area')->field('level, province, city, area, street')->where('member_id', $param['member_id'])->where('member_type', 3)->order('id desc')->find();
            if ($this_info['level'] != 3) {
                // 合伙人级别不对   直接返回空数据
                return ['code' => 200, 'data' => ['repair_num' => 0, 'repair_list' => []], 'msg' => 'success'];
            }

            $team_where['area'] = $this_info['area'];

            // 根据状态获取和合伙人负责区域处在相同区域的维修店
            if (isset($param['audit_status'])) {
                $team_where['audit_status'] = $param['audit_status'];
            }
            if (isset($param['keyword'])) {
                $team_where['repair_name'] = ['like', '%'.$param['keyword'].'%'];
            }
            $dealer_list = Db::table('mob_dealer')->where($team_where)->select();

            //dump($repairs);
            if (!$dealer_list) {  // 区域内不存在维修店  返回空
                return ['code' => 200, 'data' => ['dealer_num' => 0, 'dealer_list' => []], 'msg' => 'success'];
            }
            $dealer_num = count($dealer_list);

            //dump($wait_audit_list);
            return ['code' => 200, 'data' => ['dealer_num' => $dealer_num, 'dealer_list' => $dealer_list], 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取维修店团队
    static public function repair_team($param) {
        if( !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            // 获取合伙人负责区域的信息
            $this_info = Db::table('mob_duty_area')->field('level, province, city, area, street')->where('member_id', $param['member_id'])->where('member_type', 3)->order('id desc')->find();
            if ($this_info['level'] != 3) {
                // 合伙人级别不对   直接返回空数据
                return ['code' => 200, 'data' => ['repair_num' => 0, 'repair_list' => []], 'msg' => 'success'];
            }

            $team_where['area'] = $this_info['area'];

            // 根据状态获取和合伙人负责区域处在相同区域的维修店
            if (isset($param['audit_status'])) {
                $team_where['audit_status'] = $param['audit_status'];
            }
            if (isset($param['keyword'])) {
                $team_where['repair_name'] = ['like', '%'.$param['keyword'].'%'];
            }
            $repair_list = Db::table('mob_repair')->where($team_where)->select();
            //dump($repairs);
            if (!$repair_list) {  // 区域内不存在维修店  返回空
                return ['code' => 200, 'data' => ['repair_num' => 0, 'repair_list' => []], 'msg' => 'success'];
            }
            $repair_num = count($repair_list);

            //dump($wait_audit_list);
            return ['code' => 200, 'data' => ['repair_num' => $repair_num, 'repair_list' => $repair_list], 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取下级合伙人团队
    static public function subordinate_partner($param) {
        if( !isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try {
            $this_info = Db::table('mob_duty_area')->field('level, province, city, area, street')
                ->where('member_id', $param['member_id'])->where('member_type', 3)
                ->order('id desc')
                ->find();
            // 获取自己下级区域状态为审核通过的合伙人
            $where['da.member_type'] = 3;
            $where['da.level'] = ['gt', $this_info['level']];
            $where['p.audit_status'] = 2;
            switch ($this_info['level']) {
                case 1: // 省级
                    $where['da.province'] = $this_info['province'];
                    break;
                case 2: // 市级
                    $where['da.city'] = $this_info['city'];
                    break;
                case 3: // 区县级
                    $where['da.area'] = $this_info['area'];
                    break;
                case 4: // 街道级
                    $where['da.street'] = $this_info['street'];
                    break;
                default:
                    self::$err_code = 400083;
                    throw new \Exception('FAULT');
                    break;
            }
            $partner = Db::table('mob_duty_area')->alias('da')->field('p.*, role.sex, role.headimgurl')
                ->join('mob_partner p', 'p.member_id = da.member_id')
                ->join('mob_member_role_info role', 'p.member_id = role.member_id and role.type = 3')
                ->where($where)
                ->select();

            return ['data' => $partner, 'code' => 200, 'msg' => 'success'];
        }catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg'=>$e->getMessage()];
        }

    }

    // 获取合伙人详情
    static public function get_partner_info($param) {
        if( !isset($param['id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try {
            $partner = db('partner')->alias('p')->field('p.proposer, p.apply_time, p.audit_status, p.mobile, role.sex, role.headimgurl, da.*')
                ->join("mob_member_role_info role", 'p.member_id = role.member_id AND role.type = 3')
                ->join("mob_duty_area da", 'p.member_id = da.member_id AND da.member_type = 3')
                ->where("p.id", $param['id'])->order("da.id desc")->find();
            switch ($partner['level']) {
                case 1:
                    $where['region_id'] = $partner['province'];
                    break;
                case 2:
                    $where['region_id'] = $partner['city'];
                    break;
                case 3:
                    $where['region_id'] = $partner['area'];
                    break;
            }
            $region_name = db('region')->where($where)->value('region_name');
            $partner['address'] = $region_name;
            return ['data' => $partner, 'code' => 200, 'msg' => 'success'];
        }catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 审核接口
    static public function audit($param) {
        if (!isset($param['model']) || !isset($param['obj_id']) || !isset($param['member_id']) || !isset($param['audit_status'])) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            // 获取合伙人信息
            $partner = Db::table('mob_partner')->where('member_id', $param['member_id'])->find();

            $data = [
                'auditor' => $partner['id']
                , 'audit_status' => $param['audit_status']
                , 'audit_time' => time()
                ,'msg' => isset($param['msg']) ? $param['msg'] : ''
            ];
            Db::table('mob_' . $param['model'])->where("id", $param['obj_id'])->update($data);

            $audit_data = [
                'obj_id' => $param['obj_id'],
                'model' => $param['model'],
                'audit_status' => $param['audit_status'],
                'auditor' => $partner['proposer'],
                'audit_time' => time(),
            ];
            Db::table('mob_audit_log')->insert($audit_data);

            Db::commit();
            return ['data' => '', 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取审核进度接口
    static public function audit_schedule($param) {
        if (!isset($param['model']) || !isset($param['obj_id'])) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }
        // 启动事务
        try {
            $data = Db::table('mob_audit_log')->where('model', $param['model'])->where('obj_id', $param['obj_id'])->order('audit_time desc')->select();
            return ['data' => $data, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }
}





